<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/6/18
 * Time: 18:25
 */
namespace app\admin\controller;

use think\Controller;
use think\Db;
class Share extends Controller{
    // 定义配置项
    private $config=array(
        'APPID'              => 'wxcb63bdccb205e77b', // 微信支付APPID.
        'MCHID'              => '1537296311', // 微信支付MCHID 商户收款账号  1556016481
        'MCHIDFWS'              => '1603436544', // 微信支付MCHID 商户收款账号  1556016481
        'KEY'                => 'FwS6OzDIcTZd1q10oExFwSZr6ScKysO0', // 微信支付KEY  uniNCx3NaBq8yt7pFh4m1gY1dIqsALAy
        'KEYFWS'                => 'ykIaqVCiOW44kcYfIi6VxflcNlaDKCG5', // 微信支付KEY  uniNCx3NaBq8yt7pFh4m1gY1dIqsALAy
        'APPSECRET'          => 'd9903a933268a1452b9471e6fb5586be', // 公众帐号secert (公众号支付专用)
        'NOTIFY_URL'         => 'http://csdl.jintianjifen.cn/api/Weixin/huidiao1', // 接收支付状态的连接
        'NOTIFY_URLFWS'         => 'http://csdl.jintianjifen.cn/api/Weixin/huidiao2', // 接收支付状态的连接
        'AUTH_URL'         => 'http://csdl.jintianjifen.cn/admin/Auth2/getuser', // 获取用户信息
        'AUTH_URLSHOP'         => 'http://csdl.jintianjifen.cn/admin/Auth2/getshopuser', // 获取用户信息
    );
    public function index(){
        $data = Db::table('up_record')
            ->where('record_shop_id', 6)
            ->where('record_status', 2)
            ->sum('record_money');
        $data = Db::table('up_order')
            ->where('o_type', 'in','3')
            ->where('o_shop_id', 6)
            ->where('o_pay_status', 2)
            ->sum('o_money');
        dump($data);die;
        return $this->fetch ('share/index');
    }

    public function invite(){
        return $this->fetch ('share/invite');
    }

    public function home(){
        return $this->fetch ('share/home');
    }

    public function treasure(){
        return $this->fetch ('share/treasure');
    }

    public function posts(){
        return $this->fetch ('share/post');
    }
    public function indexnew(){
//        if(!isset($_REQUEST['shop_id']) || !$_REQUEST['shop_id']){
//            if(strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')!==false){
//                if(!session('?openid22')){
//                    $authurl = $this->config['AUTH_URLSHOP'];
//                    $appid = config('wechat')['appid'];
//                    echo "<script> location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$authurl}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'; </script>";
//                    exit;
//                }
//                $code = $_REQUEST['code'];
//                session('invite_code',$code);
//                $this->assign('useropenid',session('openid22'));
//                return $this->fetch('share/register');
//            }
//            echo '请使用微信扫码~';
//            exit();
//        }
        $shop_id = $_REQUEST['shop_id'];
        if(!isset($_REQUEST['code'])){
            echo '不合法二维码';
            exit();
        }else{
            $code = $_REQUEST['code'];
        }
        $data = [];
        if($code){
            $data = Db::table('up_u_user')
                ->where('user_invite_code', $code)
                ->find();
            if(empty($data)){
                echo '此码已不可用!';
                exit();
            }
            if($data['user_status'] != 1){
                echo '此码已暂停收款';
                exit();
            }
        }
        session('invite_code',$code);
        session('shop_id',$shop_id);
        $this->assign('data',$data);
        $this->assign('xcx_sid',$shop_id);
        $this->assign('xcx_code',$code);
        if(strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')!==false){
            session('session_type',2);
            if(!session('?openid22')){
                $authurl = $this->config['AUTH_URL'];
                $appid = config('wechat')['appid'];
                echo "<script> location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$authurl}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'; </script>";
                exit;
            }
            $this->assign('paytype',2);
            $user = Db::table('up_u_user')
                ->where('user_m_h5_wx', session('openid22'))
                ->find();
            if($user){ //存在就去主页
                $shopData = $this->recordRule($shop_id);

                $this->assign($shopData);
                $this->assign('user',$user);
                return $this->fetch('shareh/indexnew');
            }else{ //不存在就去绑定页
                $res = $this->bangdingEmpty();
                if($res['status'] == 200){
                    $url2 = "http://".$_SERVER['HTTP_HOST'];
                    echo "<script> location.href=\"$url2/admin/Share/indexnew?code=$code&shop_id=$shop_id\"; </script>";
                }else{
                    echo "{$res['msg']}";
                    exit();
                }
//                return $this->fetch('shareh/bangding');
            }

        }elseif (strpos($_SERVER['HTTP_USER_AGENT'],'AlipayClient')!==false){
            session('session_type',1);
            if(!session('?openid11')){
                echo "<script> location.href='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2019052065205188&scope=auth_user&redirect_uri=http://csdl.jintianjifen.cn/admin/Authali/getuser'; </script>";
                exit;
            }
            $this->assign('paytype',1);
            $user = Db::table('up_u_user')
                ->where('user_m_h5_zfb', session('openid11'))
                ->find();
            if($user){ //存在就去主页
                $shopData = $this->recordRule($shop_id);

                $this->assign($shopData);
                $this->assign('user',$user);
                return $this->fetch('shareh/indexnew');
            }else{ //不存在就去绑定页
                $res = $this->bangdingEmpty();
                if($res['status'] == 200){
                    $url2 = "http://".$_SERVER['HTTP_HOST'];
                    echo "<script> location.href=\"$url2/admin/Share/indexnew?code=$code&shop_id=$shop_id\"; </script>";
                }else{
                    echo "{$res['msg']}";
                    exit();
                }

//                return $this->fetch('shareh/bangding');
            }
        }else{
            echo "请使用微信扫码或者支付宝扫码！";
            exit();
        }
    }
    public function register(){
        if(strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')!==false){
            $code = $_REQUEST['code'];
            session('invite_code',$code);
            if(!session('?openid22')){
                $authurl = $this->config['AUTH_URLSHOP'];
                $appid = config('wechat')['appid'];
                echo "<script> location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$authurl}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'; </script>";
                exit;
            }
            $this->assign('useropenid',session('openid22'));
            return $this->fetch('share/register');
        }
        echo '请使用微信扫码~';exit();
    }
    /**
     * 绑定
     * @return mixed|\think\response\Json
     */
    public function bangding(){
        extract(input());
        if(!isset($phone) || !isset($code)){
            return json(['status'=>100,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status'=>100,'msg'=>'请填写正确的手机号码']);
        }
        if($code == ''){
            return json(['status'=>100,'msg'=>'请填写验证码']);
        }
        $phone_code = Db::name('phonecode')->where(['phone'=>$phone,'status'=>0,'type'=>1])->find();
        if(empty($phone_code)){
            return json(['status'=>100,'msg'=>'请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if($diff >= 30*60){
            return json(['status'=>100,'msg'=>'验证码已失效']);
        }
        if($code != $phone_code['code']){
            return json(['status'=>100,'msg'=>'验证码输入错误']);
        }
        $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
        $invite_code = session('invite_code');
        if(session('session_type') == 1){
            $fieldMww = 'user_m_h5_zfb';
            $valueMww = session('openid11');
        }else{
            $fieldMww = 'user_m_h5_wx';
            $valueMww = session('openid22');
        }
        $user_id = Db::table('up_u_user')->where($fieldMww,$valueMww)->value('user_id');
        if(!$valueMww || !$user_id) return json(['status'=>100,'msg'=>'数据错误，请刷新重试！']);
        if($user){
            if($user[$fieldMww]){
                return json(['status'=>100,'msg'=>'此手机号已被绑定']);
            }else{
                $update = [
                    $fieldMww => $valueMww
                ];
                Db::table('up_u_user')->where($fieldMww,$valueMww)->setField($fieldMww,$valueMww.'_old');
                $res = Db::table('up_u_user')->where('user_phone',$phone)->update($update);
                if($res){
                    return json(['status'=>200,'msg'=>'绑定成功！','url'=>'/admin/Share/indexnew?code=' . $invite_code . '&shop_id=' . session('shop_id')]);
                }else{
                    return json(['status'=>100,'msg'=>'绑定失败，请刷新重试！']);
                }
            }
        }else{
            Db::startTrans ();
            try{
                $token = md5(date('YmdHis') . rand(100000,999999));
                Db::name("u_user")->where($fieldMww,$valueMww)->update([
                    'user_phone'=>$phone,
                    'user_time'=>date("Y-m-d H:i:s"),
                    'user_token'=>$token,
                    'user_where'=>4,
                    $fieldMww => $valueMww
                ]);
                if($invite_code){
                    $give = Db::name('jifen_conf')->where('conf_id',16)->value('conf_rate');
                    $form = Db::name('u_user')->where('user_invite_code',$invite_code)->find();
                    if(empty($form)){
                        return json(['status'=>100,'msg'=>'邀请码输入错误']);
                    }
                    if($form['user_area'] == ''){
                        Db::name('u_user')->where(['user_id'=>$form['user_id']])->update (['user_province'=>1055,'user_city'=>1065,'user_area'=>1134]);
                        $form['user_area'] = 1134;
                    }else{
                        // 邀请人注册区没有代理
                        $is_qu = DB::name('admin')->where(['area'=>$form['user_area']])->find();
                        if (empty($is_qu)) {
                            $form['user_area'] = 1134;
                        }
                    }
                    $apithis = new \app\api\controller\Base();

                    //如果邀请方是合伙人另外奖励
                    $is_partner = DB::name('partner')
                        ->where(['par_user_id'=>$form['user_id'],'par_cancel'=>0])
                        ->find();
                    if (!empty($is_partner)) {
                        // 添加推荐人
                        DB::name('u_user')->where(['user_id'=>$user_id])->update(['user_recommend'=>$form['user_id']]);
                        // 该级别合伙人推荐粉丝奖励有效时间
                        $invite_days = DB::name('partner_class')
                            ->where(['class_id'=>$is_partner['par_class_id']])
                            ->value('class_fans_days');
                        // 邀请粉丝每天不能超过100位，超过没有奖励
                        $fans_count = DB::name('u_user')
                            ->where(['user_recommend'=>$form['user_id']])
                            ->whereTime('user_time','today')
                            ->count();
                        if ($fans_count < 100) {
                            if (time() < (strtotime($is_partner['par_add_time'])+3600*24*$invite_days)) {
                                // 合伙人一段时间内邀请粉丝积分奖励
                                $give_jifen = DB::name('partner_class')
                                    ->where(['class_id'=>$is_partner['par_class_id']])
                                    ->value('class_fans_jifen_reg');
                                // 合伙人邀请粉丝获得的奖励
                                $apithis->par_fans($user_id,3,1,$user_id);
                                // 记录获得积分
                                // DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请好友注册获得'.$give_jifen.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                // // 添加提示
                                // Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'邀请好友注册获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                                // $this->jpushUser(1,$form['user_id'],'合伙人邀请好友注册获得'.$give_jifen.'积分',json([]));
                            }else{
                                // 合伙人邀请粉丝获得的奖励
                                $apithis->par_fans($user_id,3,1,$user_id);
                            }
                        }else{
                            // 添加提示
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'当日邀请好友已达上限','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                            try {
                                $apithis->jpushUser(1,$form['user_id'],'当日邀请好友已达上限',json([]));
                            } catch (\Exception $e) {}
                        }
                    }else{
                        Db::name('admin')->where('area',$form['user_area'])->setDec('integral',$give);
                        $apithis->jifenFlow($give,$form['user_area'],$form['user_id'],'register');

                        Db::name('jifen_consume')->insert(['consume_content'=>'邀请好友获得'.$give.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);

                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'邀请好友','n_content'=>'邀请好友获得'.$give.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                        try {
                            $apithis->jpushUser(1,$form['user_id'],'邀请好友获得'.$give.'积分',json([]));
                        } catch (\Exception $e) {}
                    }
                    // 邀请的注册直接成为好友
                    $focus = Db::name('user_fellow')->where(['fellow_user_id'=>$user_id,'fellow_star_user_id'=>$form['user_id']])->find();
                    if(!$focus){
                        $time = date('Y-m-d H:i:s');
                        $param = [
                            [
                                'fellow_user_id'=>$user_id,
                                'fellow_star_user_id'=>$form['user_id'],
                                'fellow_add_time'=>$time
                            ],
                            [
                                'fellow_user_id'=>$form['user_id'],
                                'fellow_star_user_id'=>$user_id,
                                'fellow_add_time'=>$time
                            ]
                        ];
                        $res = Db::name('user_fellow')->insertAll ($param);
                        if($res){
                            Db::name('u_user')->where('user_id',$form['user_id'])->setInc('user_fans');
                            Db::name('u_user')->where('user_id',$user_id)->setInc('user_attention');
                        }
                    }
                }
                Db::name('phonecode')->where('phone',$phone)->setField ('status',1);
                Db::commit ();
                return json(['status'=>200,'msg'=>'成功','user_id'=>$user_id,'url'=>'/admin/Share/indexnew?code=' . $invite_code . '&shop_id=' . session('shop_id')]);
            }catch (\Exception $e){
                Db::rollback ();
                return json(['status'=>100,'msg'=>'注册失败，请刷新重试！']);
            }
        }
    }
    public function gobangding(){
        $invite_code = session('invite_code');
        $this->assign('invite_code',$invite_code);
        return $this->fetch('shareh/bangding');
    }
    /**
     * 绑定
     * @return mixed|\think\response\Json
     */
    public function bangdingEmpty(){
        extract(input());
        $invite_code = session('invite_code');
        if(session('session_type') == 1){
            $fieldMww = 'user_m_h5_zfb';
            $valueMww = session('openid11');
        }else{
            $fieldMww = 'user_m_h5_wx';
            $valueMww = session('openid22');
        }
        Db::startTrans ();
        try{
            $token = md5(date('YmdHis') . rand(100000,999999));
            $user_id = Db::name("u_user")->insertGetId([
                'user_username'=>session('nickname22'),
                'user_image'=>session('thumb22'),
                'user_time'=>date("Y-m-d H:i:s"),
                'user_token'=>$token,
                'user_where'=>4,
                $fieldMww => $valueMww
            ]);
//            if($invite_code){
//                $give = Db::name('jifen_conf')->where('conf_id',16)->value('conf_rate');
//                $form = Db::name('u_user')->where('user_invite_code',$invite_code)->find();
//                if(empty($form)){
//                    return ['status'=>100,'msg'=>'邀请码输入错误'];
//                }
//                if($form['user_area'] == ''){
//                    Db::name('u_user')->where(['user_id'=>$form['user_id']])->update (['user_province'=>1055,'user_city'=>1065,'user_area'=>1134]);
//                    $form['user_area'] = 1134;
//                }else{
//                    // 邀请人注册区没有代理
//                    $is_qu = DB::name('admin')->where(['area'=>$form['user_area']])->find();
//                    if (empty($is_qu)) {
//                        $form['user_area'] = 1134;
//                    }
//                }
//                $apithis = new \app\api\controller\Base();
//
//                //如果邀请方是合伙人另外奖励
//                $is_partner = DB::name('partner')
//                    ->where(['par_user_id'=>$form['user_id'],'par_cancel'=>0])
//                    ->find();
//                if (!empty($is_partner)) {
//                    // 添加推荐人
//                    DB::name('u_user')->where(['user_id'=>$user_id])->update(['user_recommend'=>$form['user_id']]);
//                    // 该级别合伙人推荐粉丝奖励有效时间
//                    $invite_days = DB::name('partner_class')
//                        ->where(['class_id'=>$is_partner['par_class_id']])
//                        ->value('class_fans_days');
//                    // 邀请粉丝每天不能超过100位，超过没有奖励
//                    $fans_count = DB::name('u_user')
//                        ->where(['user_recommend'=>$form['user_id']])
//                        ->whereTime('user_time','today')
//                        ->count();
//                    if ($fans_count < 100) {
//                        if (time() < (strtotime($is_partner['par_add_time'])+3600*24*$invite_days)) {
//                            // 合伙人一段时间内邀请粉丝积分奖励
//                            $give_jifen = DB::name('partner_class')
//                                ->where(['class_id'=>$is_partner['par_class_id']])
//                                ->value('class_fans_jifen_reg');
//                            // 合伙人邀请粉丝获得的奖励
//                            $apithis->par_fans($user_id,3,1,$user_id);
//                            // 记录获得积分
//                            // DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请好友注册获得'.$give_jifen.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
//                            // // 添加提示
//                            // Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'邀请好友注册获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
//                            // $this->jpushUser(1,$form['user_id'],'合伙人邀请好友注册获得'.$give_jifen.'积分',json([]));
//                        }else{
//                            // 合伙人邀请粉丝获得的奖励
//                            $apithis->par_fans($user_id,3,1,$user_id);
//                        }
//                    }else{
//                        // 添加提示
//                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'当日邀请好友已达上限','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
//                        try {
//                            $apithis->jpushUser(1,$form['user_id'],'当日邀请好友已达上限',json([]));
//                        } catch (\Exception $e) {}
//                    }
//                }else{
//                    Db::name('admin')->where('area',$form['user_area'])->setDec('integral',$give);
//                    $apithis->jifenFlow($give,$form['user_area'],$form['user_id'],'register');
//
//                    Db::name('jifen_consume')->insert(['consume_content'=>'邀请好友获得'.$give.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
//
//                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'邀请好友','n_content'=>'邀请好友获得'.$give.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
//                    try {
//                        $apithis->jpushUser(1,$form['user_id'],'邀请好友获得'.$give.'积分',json([]));
//                    } catch (\Exception $e) {}
//                }
//                // 邀请的注册直接成为好友
//                $focus = Db::name('user_fellow')->where(['fellow_user_id'=>$user_id,'fellow_star_user_id'=>$form['user_id']])->find();
//                if(!empty($focus)){
//                    return ['status'=>100,'msg'=>'已关注该好友'];
//                }
//                $time = date('Y-m-d H:i:s');
//                $param = [
//                    [
//                        'fellow_user_id'=>$user_id,
//                        'fellow_star_user_id'=>$form['user_id'],
//                        'fellow_add_time'=>$time
//                    ],
//                    [
//                        'fellow_user_id'=>$form['user_id'],
//                        'fellow_star_user_id'=>$user_id,
//                        'fellow_add_time'=>$time
//                    ]
//                ];
//                $res = Db::name('user_fellow')->insertAll ($param);
//                if($res){
//                    Db::name('u_user')->where('user_id',$form['user_id'])->setInc('user_fans');
//                    Db::name('u_user')->where('user_id',$user_id)->setInc('user_attention');
//                }
//            }
            Db::commit ();
            return ['status'=>200,'msg'=>'成功'];
        }catch (\Exception $e){
            Db::rollback ();
            return ['status'=>100,'msg'=>'注册失败，请刷新重试！'];
        }
    }
    public function inputpass()
    {
        return view('shareh/inputPassword');
    }
    public function setpass()
    {
        if(session('session_type') == 1){
            $fieldMww = 'user_m_h5_zfb';
            $valueMww = session('openid11');
        }else{
            $fieldMww = 'user_m_h5_wx';
            $valueMww = session('openid22');
        }
        $user = Db::name('u_user')->where($fieldMww,$valueMww)
            ->field('user_id,user_phone')->find();
        if(!$user){
            echo '请刷新重试！';
            exit();
        }else{
            $user_phone = $user['user_phone'];
            $this->assign('user_phone2',$user_phone);
            $user_phone = substr($user_phone,0,4) . '****' . substr($user_phone,7,4);
            $this->assign('user_phone',$user_phone);
            $this->assign('user_id',$user['user_id']);
            return $this->fetch ('shareh/setPass');
        }
    }
    public function QRcodePayH5(){
        extract (input());
        if(session('session_type') == 1){
            $fieldMww = 'user_m_h5_zfb';
            $valueMww = session('openid11');
        }else{
            $fieldMww = 'user_m_h5_wx';
            $valueMww = session('openid22');
        }
        $shop_id = session('shop_id');
        $user_id = Db::name('u_user')->where($fieldMww,$valueMww)->value('user_id');
        $shop = Db::name('shop')->where(['shop_id'=>$shop_id])->find();
        if(!$user_id || $type == ''){
            return json(['status'=>100,'msg'=>'参数错误，请刷新页面']);
        }
        if(!$shop_id || empty($shop)){
            if($type == 1) return 1;
            return json(['status'=>100,'msg'=>'收款码错误']);
        }
        if($type == 2){
            if((int)$integral <= 0) return json(['status'=>100,'msg'=>'积分输入错误']);
//            if(md5($passwordStr) != $payPass) return json(['status'=>1000,'msg'=>'密码错误！']);
        }
        if($type == 1){
            if (preg_match('/\.\d{3,}/', $money)) {
                return 5;
            }
            $intMoney = $money*100;
            if($intMoney <= 0){
                return 4;
            }
            $intMoneyOld = $money*100;
            $payment_type = session('session_type');
        }
        $uid = '';
        $uname = '';
        $title = '';
        $image = '';
        $real_pay = '';
        $all_pay = $money;
        $red_give = '';
        Db::startTrans ();
        try{
            $apithis = new \app\api\controller\Base();
            $order = $apithis->getOrderNumber ();
            $param = [
                'record_number'=>$order,
                'record_user_id'=>$user_id,
                'record_shop_id'=>$shop_id,
                'record_type'=>$type,
                'record_payment_type'=>$payment_type,
                'record_status'=>1,
                'record_jifen'=>$integral,
                'record_money'=>$money,
                'record_remark'=>$remark,
                'record_zhekou'=>1,
                'record_add_time'=>date("Y-m-d H:i:s"),
                'record_give_jifen'=>0,
                'record_lose_time'=>date("Y-m-d H:i:s",strtotime ("+15 minutes"))
            ];
            if($shop['shop_ratio'] && $shop['shop_ratio'] >= '9.8' && $shop['shop_time'] > '2022-06-15 10:51:00') $param['record_zhekou'] = 2;
            if($type == 1 && $money != ''){
                $param['record_give_jifen'] = $record_give_jifen;
//                $conf_rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
//                $shop_ratio = DB::name('shop')->where('shop_id',$shop_id)->value('shop_ratio');
//                if (!empty($shop_ratio)) {
//                    $ratio = (10-$shop_ratio)/10;
//                    $param['record_give_jifen'] = round(($money*$ratio)/$conf_rate,0);
//                }else{
//                    $rule = Db::name('record_rule')->where(['rule_shop_id'=>$shop_id])->order("rule_cash DESC")->select ();
//                    if(!empty($rule)){
//                        $ruleForCash = array_column ($rule,'rule_cash');
//                        $ruleForIntegral = array_column ($rule,'rule_jifen');
//                        foreach($ruleForCash as $key=>$vo){
//                            if($money >= $vo){
//                                $param['record_give_jifen'] = $ruleForIntegral[$key];
//                                break;
//                            }
//                        }
//                    }
//                }
            }
            $give_jifen = $param['record_give_jifen'];
            $record_id = Db::name('record')->insertGetId ($param);
            if($type == 1){
//                if($param['record_give_jifen'] > 0){
//                    $stay = Db::name('record')->where(['record_id'=>['neq',$record_id],'record_type'=>1,'record_status'=>1,'record_shop_id'=>$shop_id])->sum ('record_give_jifen');
//                    if($param['record_give_jifen'] > $shop['shop_integral'] - $stay){
//                        try{
//                            $apithis->jpushShop (1,$shop_id,'您的店铺积分不足',json([]));
//                        }catch (\Exception $e){
//                        }
//                        Db::name('notice')->insert (['n_to'=>2,'n_title'=>'积分提醒','n_content'=>'您的店铺积分不足','n_images'=>'','n_type'=>1,'n_user_id'=>$shop_id,'n_read'=>',0,','n_delete'=>',0,','n_time'=>date('Y-m-d H:i:s')]);//消息
//                        if($type == 1) return 2;
//                        return json(['status'=>100,'msg'=>'商家积分不足']);
//                    }
//                }
                //-----------------------------算红包start 暂时关闭，开的时候直接打开即可--------------------------------------
                if($shop['shop_qu_id']){
                    //1、先纠正一下
                    $time = time();
                    $one_hour_ago = date("Y-m-d H:i:s", ($time - 300));
                    Db::name('m_red_user')
                        ->where('ru_user_id','>',0)
                        ->where('ru_status',1)
                        ->where('ru_get_time','<=',$one_hour_ago)
                        ->setField('ru_user_id',0);
                    //2、找一个红包并赋值(先筛除一天一区领一个，且如果标中未支付，则还是这个)
                    $where = [
                        'red_user_id' => ['>',0]
                    ];
                    $whereNo = Db::name('m_red_user')
                        ->where('ru_user_id',$user_id)
                        ->where('ru_status',2)
                        ->whereTime('ru_get_time','today')
                        ->group('ru_red_id')
                        ->column('ru_red_id');
                    if($whereNo){
                        $whereRed = Db::name('m_red')
                            ->where('red_user_area',$shop['shop_qu_id'])
                            ->where('red_status',2)
                            ->where('red_id','in',$whereNo)
                            ->column('red_user_id');
                        if($whereRed){
                            $where = [
                                'red_user_id' => ['not in',$whereRed]
                            ];
                        }
                    }
                    $redData = Db::name('m_red r')
                        ->join('m_red_user ru','r.red_id = ru.ru_red_id','left')
                        ->where(['red_status' => 2 ,'ru_user_id' => $user_id,'red_user_area' => $shop['shop_qu_id']])
                        ->where('ru_status',1)
                        ->where($where)
                        ->where('ru_money','<',$money)
                        ->find();
                    if(!$redData){
                        $redData = Db::name('m_red r')
                            ->join('m_red_user ru','r.red_id = ru.ru_red_id','left')
                            ->where(['red_status' => 2 ,'ru_user_id' => 0,'red_user_area' => $shop['shop_qu_id']])
                            ->where('ru_money','<',$money)
                            ->where($where)
                            ->order('red_add_time desc')
                            ->find();
                    }
                    if($redData){
                        $hehuoData = Db::name('u_user')
                            ->where(['user_id' => $redData['red_user_id']])
                            ->field('user_username,user_phone,user_m_name')
                            ->find();
                        if($hehuoData['user_username'] == $hehuoData['user_phone']){
                            $hehuoData['user_username'] = substr($hehuoData['user_username'],0,3) . '****' . substr($hehuoData['user_username'],7,4);
                        }
                        $uid = $redData['red_user_id'];
                        $uname = $hehuoData['user_m_name'] ?: $hehuoData['user_username'];
                        $title = $redData['red_title'];
                        $image = $redData['red_image'];
                        $real_pay = $money - $redData['ru_money'];
                        $red_give = $redData['ru_money'];
                        //3、改一下当前红包的相关值
                        Db::name('m_red_user')
                            ->where('ru_id',$redData['ru_id'])
                            ->update([
                                'ru_user_id' => $user_id,
                                'ru_get_time' => date('Y-m-d H:i:s')
                            ]);
                        //4、用户实际应该付的款
                        $moneyOld = $money - $redData['ru_money'];
                        $intMoneyOld = $moneyOld*100;
                        if($intMoneyOld <= 0){
                            Db::rollback ();
                            return 4;
                        }
                        Db::name('record')->where('record_id',$record_id)
                            ->setField('record_ru_id',$redData['ru_id']);
                    }
                }
                $new_msg = ['uid' => $uid,'uname' => $uname,'title' => $title,'image' => $image,'real_pay' => $real_pay,'red_give' => $red_give,'all_pay' => $all_pay,'give_jifen' => $give_jifen];
                $new_msg = implode('&',$new_msg);
                //-----------------------------算红包 end--------------------------------------
                if($payment_type == 1){
                    import('alipay.aop.AopClient', EXTEND_PATH);
                    import('alipay.aop.request.AlipayTradeWapPayRequest', EXTEND_PATH);
                    $aop = new \AopClient ();
                    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                    $aop->appId = '2019052065205188';
                    $aop->rsaPrivateKey = 'MIIEpQIBAAKCAQEAlnemjJ0OSNt1SzGhSkdWtmK7S1FKSwpcRiCIfVF0ViP3ZAB8MlpFTdQ7Zq0mXbIRHU3V5HCsmJLtvuyws+QJY90BMGxlItKPXc+5ZnRqIJIaBd99qlCX/CNCZA4mmsocMmz/LT41QMv5SMB1PiBPJqQme/WiaBZlFcmCETU8e2n/YBlGj3GaDy5tWy9W6qHEUc/1H74LEDsQJn176rKCzEfAUwaZOv6eoElGzXfrgXmgvbXpuBvAY9TwQ0rK6YGMeO5fUM157Ti/4/cWIxVFUj06zi5aNgGNCrv6jxDZPG4l+sQeUay9xc4sClHI8YXw6jq6LJHdr8uif5BW6YhsqQIDAQABAoIBAH3+xynrwbBkhD1o26R1RDkJR8hz04AutsHKMECv2njfOSM1/Mm1KV9Ynj0GNKA0oXwmVzso1n4UWpyLWhPomaxTvdEskyuroX1umdMfHFcVwFC2qmXZgssRQ2DBMLZhE2duOedKthECPEYdUo+pQl4bCla2gz4hspeh2xZJu9Gi0ga3LHfPPFbm4P4V9yf60kAkr6CIHYJgK1j7ECfZmhj/FiS/MGk+X6ognPSTAAWaycDrCPfrTmMiYAScRZ8TOpTUW8AX+SIrnhVfEzRrw1qEc1Nhtd9aGY9SUfLQwwd6RB1wmzBSa4H55b316yjqUZGRBWvrE8/4Pl1vK8In5/kCgYEAx4NoUTyiWUVR/GdywThsW1FJ3j2Xz6OzFjMEkMuLOeAj88zk4cqalTBZzlNs/BLf40GmBTJuDooEfKNR7mjY2Cy8pfkr8Ez5r1RC8uU1y3+Dd2MXvSbwlu4l9LqAMD8XFuVSdSuezd1wh7/gDKuBz4JOEI4x0vUTGrmnIc4VcRMCgYEAwRFtSwzf+KsrdKbKGQqGRTVfZluwjirjZnXfco7VBj1ZoGBNcv5i7oS68FmAKUiA1SfZBlQxKMju4Uq73LOYfZ/z4irXCcd74mb7qpwi9/XmXEc/b09ZPoqfQNrGgMbw/jK+19cDqnR0jpmGbtneIMWmFAB3WVZXZXpxyjp0HtMCgYEAt6yEZvV5SNIGjmX2QWfeaZtGc/EkR6YfAvro4xxgCmIM9y/ULwJEmcAvjUFEfjQqJZ+UZghtRblONChvDxs7NpjI+8uO5eUXoI/kKpVVlwjHUSvK+PpWV7za+JiR1tjeOtfXt8L2qfOI25CLhV6HXTBLCfa+a8XvVpVABmEhYD0CgYEAisY++/omJzTKCJA2pic1ehuyFf4D+zyCtcw2L77RCiog+TEfmm+VpwKK6GY8w+/UguKgkXcE2t8LLa8tN6d0DaBiigfnB6V2u7bwYKLYU8lRqrSfuR+c82JqtBBNLJVS9jR9juGDRgttGG7r/VPm4UGQbcIkB3gTW+LWVdkMTHcCgYEArXyiBWXQN2yK9yK86/23GupMQ6jb6kGP0PjtMLBZ74W6n3GCQQ34Q9SzL4Ea2ZcWtHFoLmirjvQJAvq98lHCdbtUY62l7CT99PQxXw87+OEHeXWIeyhvLl9cIQtlS1E9HQydWIjGtpSGSE8FJG0TCWsYuzgTm3VmNbxE3CnTjWg=';
                    $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwamELkZPcThxb5wg789OSjkkfbFcwlb8KavQ1TKdoa7ZR3w6QdzYLXkS/aqGgNjT0+WJm/yup+wzr7G/o7POY8PlUvaLofxOw/CiA8NLAki+hrmFZhfPUrV218u5cNKYaQx5PIbjpSxI/fwOPXIJ9ZV5LJUouA1EbGthrskiM/lbHHYonfwdr94b6I+e2HuiRMhvRgVI55a8tPMIdJvO+u4GQLLbtOlL0aZ+cOAKvz7T9eSMwvdzDs0IYRQgasKgyyVdvxOB0XaCfYPtQ8CC+CQs53b+EfX6A/WG+cgXYR75MVHzHWTP4Qg+EszEOxIfcrJkiBa4gd+Fs2wPp73HrQIDAQAB';
                    $aop->apiVersion = '1.0';
                    $aop->postCharset='UTF-8';
                    $aop->format='json';
                    $aop->signType='RSA2';
                    $request = new \AlipayTradeWapPayRequest ();
                    $request->setNotifyUrl('http://csdl.jintianjifen.cn/api/Ali/huidiao1');
                    $request->setReturnUrl('https://csdl.jintianjifen.cn/admin/test/test?' . $new_msg);
                    $request->setBizContent("{" .
                        "    \"body\":\"QRcodePay\"," .
                        "    \"subject\":\"扫码支付\"," .
                        "    \"out_trade_no\":\"$order\"," .
                        "    \"timeout_express\":\"90m\"," .
                        "    \"total_amount\":$money," .
                        "    \"product_code\":\"QUICK_WAP_WAY\"" .
                        "  }");
                    $result = $aop->pageExecute ( $request);
                    Db::commit ();
                    echo $result;
                    exit();
                }else if($payment_type == 2){
                    $mwwsign = 0;
                    $payorder = array();
                    $payorder['attach'] = "QRcodePay"; // 描述
                    $payorder['body'] = "扫码支付"; // 描述
                    $payorder['total_fee'] = $intMoney; // 订单金额
                    $payorder['out_trade_no'] = $order; // 订单号
                    $payorder['product_id'] = ''; // 产品ID
                    $payorder['trade_type'] = 'JSAPI'; // 类型
                    //---------------------------------二级商户---------------------------------------
                    $shop_copy = Db::name('shop_copy')->where('sc_shop_id',$shop_id)->field('sc_mch_id')->find();
                    if($shop_copy && $shop_copy['sc_mch_id']){
                        //小票信息
                        $xiaopiao = ['uid' .'='. $uid,'uname' .'='. $uname,'title' .'='. $title,'image' .'='. urlencode($image),'real_pay' .'='. $real_pay,'red_give' .'='. $red_give,'all_pay' .'='. $all_pay,'give_jifen' .'='. $give_jifen];
                        $addUpdate = [
                            'record_fws' => 2,
                            'record_sch_id' => $shop_copy['sc_mch_id'],
                            'record_xiaopiao' => implode('&',$xiaopiao)
                        ];
                        $add_res = $this->addFen($shop_copy['sc_mch_id']);
                        if($add_res['status'] != 200){
                            return 3;
                        }
                        $payorder['mch_id']=$this->config['MCHIDFWS'];
                        $payorder['sub_mch_id']=$shop_copy['sc_mch_id'];
                        if($give_jifen > 0){
                            $payorder['profit_sharing'] = 'Y';
                            $addUpdate['record_fen'] = 2;
                        }
                        Db::name('record')->where(['record_id'=>$record_id])->update($addUpdate);
                        $mwwsign = 1;
                    }else{
                        $payorder['total_fee'] = $intMoneyOld;
                        $payorder['mch_id']=$this->config['MCHID'];
                    }
                    $respont = $this->WeChatPayReady($payorder,$mwwsign);
                    if($respont['status'] == 200){
                        Db::commit ();
                        $json = $this->getOrder($respont['msg'],$mwwsign);
                        return view('shareh/pay_done',['json'=>$json,'uid' => $uid,'uname' => $uname,'title' => $title,'image' => urlencode($image),'real_pay' => $real_pay,'red_give' => $red_give,'all_pay' => $all_pay,'give_jifen' => $give_jifen]);
                    }else{
                        return 3;
                    }
                }
            }else{
                $back = $apithis->consume($user_id,$integral,$shop_id);
                $rate = Db::name('jifen_conf')->where('conf_id',2)->value ('conf_rate');
                if($back['status'] == 100){
                    return json($back);
                }else{
                    Db::name('jifen_consume')->insert (['consume_content'=>'扫码支付给“'.$shop['shop_name'].'”'.$integral.'积分','consume_user_id'=>$user_id,'consume_add_time'=>date("Y-m-d H:i:s")]);
                    Db::name('record')->where(['record_id'=>$record_id])->update(['record_status'=>2,'record_pay_time'=>date("Y-m-d H:i:s"),'record_shop_balance'=>$shop['shop_balance']+$realInputMoney,'record_money'=>$realInputMoney]);
                    Db::name('shop')->where('shop_id',$shop_id)->setInc ('shop_balance',$realInputMoney);
                    Db::name('shop')->where('shop_id',$shop_id)->setInc('shop_all_balance',$realInputMoney);
                    try{
                        $yuan = $realInputMoney;
                        $apithis->sayMyName($shop_id,$yuan,0,$order,2);
                        $apithis->jpushShop(1,$shop_id,"收款{$integral}积分",['type2' => 1024,'msg' => "积分买单到账{$yuan}元"]);
                    }catch (\Exception $e){
                    }
                    Db::commit ();
                    return json(['status'=>200,'msg'=>'支付成功']);
                }
            }
        }catch (\Exception $e){
            Db::rollback ();
            return json(['status'=>100,'msg'=>"支付失败"]);
        }
    }
	public function download(){
        return $this->fetch('share/download');
    }
    //------------------------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------------------------
    /**
     * 统一下单
     * @param  array $order 订单 必须包含支付所需要的参数 body(产品描述)、total_fee(订单喵额)、out_trade_no(订单号)、product_id(产品id)、trade_type(类型：JSAPI，NATIVE，APP)
     */
    public function WeChatPayReady($order,$type=0){
        // 获取配置项
        $weixinpay_config=$this->config;
        $config=array(
            'appid'=>$weixinpay_config['APPID'],
//            'mch_id'=>$weixinpay_config['MCHID'],
            'nonce_str'=>'test',
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
            'openid'=>session('openid22'),
            'notify_url'=>$weixinpay_config['NOTIFY_URL']
        );
        if($type > 0){
            $config['notify_url'] = $weixinpay_config['NOTIFY_URLFWS'];
        }
        // 合并配置数据和订单数据
        $data=array_merge($order,$config);

        // 生成签名
        $sign=$this->makeSign($data,$type);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件
        $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        $result=$this->toArray($response);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $res = [
                'status' => 200,
                'msg' => $result['prepay_id']
            ];
        }else{
            $res = [
                'status' => 0,
                'msg' => $result['return_msg']
            ];
        }
        return $res;
    }

    /**
     * 获取时间
     * @return array
     */
    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }

    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    /**
     * 验证
     * @return array 返回数组格式的notify数据
     */
    public function huidiao(){
        // 获取xml
        $xml=file_get_contents('php://input', 'r');
        // 转成php数组
        $getInfo=$this->toArray($xml);
//        $this->write_admin_log($getInfo);
        // 保存原sign
        $data_sign=$getInfo['sign'];
        // sign不参与签名
        unset($getInfo['sign']);
        $sign=$this->makeSign($getInfo);
        // 判断签名是否正确  判断支付状态
        if ($sign===$data_sign && $getInfo['return_code']=='SUCCESS' && $getInfo['result_code']=='SUCCESS') {
            $num = $getInfo['out_trade_no']; // 订单号
            $backno = $getInfo['transaction_id'];//订单号
            $status = Db::table('up_offline_order')->where('orderno',$num)->value('status');
            if($status == 1){
                $res = Db::table('up_offline_order')->where('orderno',$num)->update([
                    'status' => 2,
                    'backno' => $backno,
                    'time' => date('Y-m-d H:i:s')
                ]);
                if($res){
                    $result = true;
                }else{
                    $result = false;
                }
            }else{
                $result = true;
            }
        } else{
            $result = false;
        }
        // 返回状态给微信服务器----------------
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
    }

    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function makeSign($data,$signty=0){
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $config=$this->config;
        if($signty > 0){
            $config['KEY'] = $config['KEYFWS'];
        }
        $string_sign_temp=$string_a."&key=".$config['KEY'];
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        if($signty > 1){
            $sign = hash_hmac("sha256",$string_sign_temp ,$config['KEY']);
        }
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
    public function toArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }

    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function toXml($data){
        //var_dump($data);
        if(!is_array($data) || count($data) <= 0){
            //throw new WxPayException("数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    //数组转xml
    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    //post https请求，CURLOPT_POSTFIELDS xml格式
    public function postXmlCurl($xml,$url,$second=30, $useCert=false, $sslcert_path='', $sslkey_path='')
    {
        //初始化curl
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        if($useCert == true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
//            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
//			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);//严格校验
            //设置证书
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, $sslcert_path);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, $sslkey_path);
//            curl_setopt($ch,CURLOPT_CAINFO, __DIR__.'/cert/rootca.pem');
        }
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data)
        {
            curl_close($ch);
            return $data;
        }
        else
        {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }

    //获取指定长度的随机字符串
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }

    //执行第二次签名，才能返回给客户端使用(微信浏览器H5支付的话有所区别)
    public function getOrder($prepayId,$oldSign=0){
        $data["appId"] = $this->config["APPID"];
        $data["nonceStr"] = $this->getRandChar(32);
        $data["package"] = "prepay_id=$prepayId";
        $data["signType"] = 'MD5';
        $data["timeStamp"] = strval(time());
        $s = $this->makeSign($data, $oldSign);
        $data["paySign"] = $s;
        return json_encode($data);
    }

    /**
     * 获取当前服务器IP
     * @return string
     */
    public  function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }
    //----------------------------------------------------------------------------------------
    public function recordRule($shop_id){
        extract (input());
        $rule = Db::name("record_rule")
            ->where(['rule_shop_id'=>$shop_id])
            ->order('rule_cash ASC')
            ->select();
        //-----
        $conf_rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');
        $shop_ratio = DB::name('shop')->where('shop_id',$shop_id)->value('shop_ratio');
        if (!empty($shop_ratio) && !empty($rule)) {
            foreach($rule as $k => $v){
                $ratio = (10-$shop_ratio)/10;
                $rule[$k]['rule_jifen'] = round(($v['rule_cash']*$ratio)/$conf_rate,0);
            }
        }
        //-----
        $data = Db::name('jifen_conf')
            ->where(['conf_id'=>['in','23,24']])
            ->select ();
        $shop_name = Db::name('shop')->where(['shop_id'=>$shop_id])->field('shop_name,shop_img')->find();
        if(empty($shop_ratio)){
            $typetypeee = 1;
            $ratio = 0;
            $ratio2 = 0;
        }else{
            $typetypeee = 2;
            $ratio = (10-$shop_ratio)/10;
            $ratio2 = $shop_ratio;
        }
        return ['shopMsg'=>$rule,'shopMsgJson'=>json_encode($rule),'shopData'=>$data,'shopName'=>$shop_name['shop_name'],'shopImg'=>$shop_name['shop_img'],'shopType'=>$typetypeee,'shopRatio'=>$ratio,'shopRatio2'=>$ratio2,'conf_rate'=>$conf_rate];
    }
    //----------------------------------------------------------------------------------------
    public function addFen($son_mchid){
        $url = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";
        $data["appid"] = $this->config['APPID'];//微信开放平台审核通过的应用APPID
        $data["mch_id"] = $this->config['MCHIDFWS'];//商户号
        $data["sub_mch_id"] = $son_mchid;//
        $data["nonce_str"] = $this->getRandChar(32);//随机字符串
        $data["sign_type"] = 'HMAC-SHA256';
        $data["receiver"] = json_encode([
            'type' => 'MERCHANT_ID',
            'account' => '1603445926',
            'name' => "滁州市爱小屏信息科技有限公司",
            'relation_type' => 'SERVICE_PROVIDER',
        ],JSON_UNESCAPED_UNICODE);
        $sign = $this->makeSign($data,2);
        $data['sign'] = $sign;
        $xml = $this->toXml($data);
        $response = $this->postXmlCurl($xml, $url);
//        dump($response);die;
        $responseArr = $this->toArray($response);
        if (!is_array($responseArr) || count($responseArr) <= 0) {
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        } else if ($responseArr['return_code'] == 'FAIL') {
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        } else {
            if ($responseArr['result_code'] == 'FAIL') {
                $return['msg'] = $responseArr['err_code_des'];
                $return['status'] = 0;
            } else {
                $return['text'] = $responseArr;
                $return['status'] = 200;
            }
        }
        return $return;
    }
    public function fenMoney(){
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $second_30 = date("Y-m-d H:i:s",(strtotime("{$today}")-30));
        $datas = Db::table('up_record')->alias('r')
            ->join('up_shop_copy sc','r.record_shop_id=sc.sc_shop_id','LEFT')
            ->where('record_status',2)
            ->where('record_fws',2)
            ->where('record_fen',2)
            ->where('record_fen_money','>',0)
            ->where('record_pay_time','<=',$second_30)
            ->page(1,5)
            ->field('record_id,record_number,record_third_number,sc_mch_id,record_sch_id,record_fen_money')
            ->select();
//        dump($datas);die;
        if($datas){
            $url = "https://api.mch.weixin.qq.com/secapi/pay/profitsharing";
            $data["appid"]        = $this->config['APPID'];//微信开放平台审核通过的应用APPID
            $data["mch_id"] 	  = $this->config['MCHIDFWS'];//商户号
            $data["sign_type"] = 'HMAC-SHA256';//随机字符串
            foreach ($datas as $k=>$v){
                $son_mchid = $v['sc_mch_id'];
				if($v['record_sch_id']) $son_mchid = $v['record_sch_id'];
				if($son_mchid == '1603445926'){
                    Db::table('up_record')->where('record_id',$v['record_id'])->setField('record_fen',3);
                }else{
                    $transaction_id = $v['record_third_number'];
                    $refundNo = $v['record_number'];
                    $amount = $v['record_fen_money'];
                    $data["nonce_str"] 	  = $this->getRandChar(32);//随机字符串
                    $data["sub_mch_id"]   = $son_mchid;
                    $data["transaction_id"]   = $transaction_id;
                    $data["out_order_no"]   = $refundNo;
                    $data["receivers"]   = json_encode([[
                        'type' => 'MERCHANT_ID',
                        'account' => '1603445926',
                        'amount' => $amount*100,
                        'description' => '服务商H5扫码支付积分款',
                    ]],JSON_UNESCAPED_UNICODE);
                    $sign=$this->makeSign($data,2);
                    $data['sign']=$sign;
                    $xml=$this->toXml($data);
                    $response 	= $this->postXmlCurl($xml, $url,'',true,ROOT_PATH.'/public/cert/apiclient_cert.pem',ROOT_PATH.'/public/cert/apiclient_key.pem');
                    $responseArr=$this->toArray($response);
//                dump($responseArr);die;
                    if($responseArr['return_code'] == 'SUCCESS' && $responseArr['result_code'] == 'SUCCESS'){
                        Db::table('up_record')->where('record_id',$v['record_id'])->setField('record_fen',3);
                    }
//                    else{
////                        dump($responseArr);die;
//                    }
                }

            }
        }
        exit();
    }
    //--------------------语音播报设备---------------------------
    public function equipment()
    {
        if(!isset($_REQUEST['urlsecretkey']) || !$_REQUEST['urlsecretkey']){
            echo '不合法二维码';
            exit();
        }
        $ss_urlparam = $_REQUEST['urlsecretkey'];
        $data = Db::table('up_shop_ercode')
            ->where('ss_urlparam', $ss_urlparam)
            ->find();
        if(!$data){
            echo '此二维码数据有误！';
            exit();
        }else{
            if($data['ss_shop_id'] <= 0){
                $this->assign('data',$data);
                return $this->fetch('shareh/ercode');
            }else{
                $user_id = Db::table('up_shop')
                    ->where('shop_id', $data['ss_shop_id'])
                    ->value('shop_user_id');
                $user_level = Db::name('u_user')->where('user_id', $user_id)->field('user_invite_code,user_level')->find();
                if ($user_level['user_level'] != 1) {
                    $this->redirect(url('admin/share/indexnew') . '?code=' . $user_level['user_invite_code'] . '&shop_id=' . $data['ss_shop_id']);
                } else {
                    $this->redirect(url('admin/share/indexnew') . '?code=&shop_id=' . $data['ss_shop_id']);
                }
            }
        }
    }
    public function bindShopCode()
    {
        extract(input());
        if ($code == '') {
            return json(['status' => 100, 'msg' => '请填写验证码']);
        }
        $phone_code = Db::name('phonecode')->where(['phone' => $phone, 'status' => 0, 'type' => 1])->find();
        if (empty($phone_code)) {
            return json(['status' => 100, 'msg' => '请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if ($diff >= 30 * 60) {
            return json(['status' => 100, 'msg' => '验证码已失效']);
        }
        if ($code != $phone_code['code']) {
            return json(['status' => 100, 'msg' => '验证码输入错误']);
        }
        $shop = Db::table('up_shop')
            ->where('shop_account', $phone)
            ->field('shop_id,shop_attestation,shop_status')
            ->find();
        if (!$shop) return json(['status' => 100, 'msg' => '您还不是商家']);
        if ($shop['shop_attestation'] != 2) return json(['status' => 100, 'msg' => '只有认证通过的商家才可以绑定']);
        if ($shop['shop_status'] != 1) return json(['status' => 100, 'msg' => '此账号已被冻结，请联系管理员']);
        $have = Db::table('up_shop_ercode')
            ->where('ss_shop_id', $shop['shop_id'])
            ->find();
        if ($have) return json(['status' => 100, 'msg' => '此商家已经绑定过设备了']);
        $ss_about_name = strtoupper($ss_about_name);
        $have = Db::table('up_shop_ercode')
            ->where('ss_about_name', $ss_about_name)
            ->find();
        if ($have) return json(['status' => 100, 'msg' => '此设备已经绑定商家了']);
        $have = Db::table('up_shop_ercode')
            ->where('ss_uni_name', $ss_about_name)
            ->find();
        if (!$have) return json(['status' => 100, 'msg' => '无此设备，请检查好填写']);
        $res = Db::table('up_shop_ercode')
            ->where('ss_urlparam', $ss_urlparam)
            ->update([
                'ss_shop_id' => $shop['shop_id'],
                'ss_about_name' => $ss_about_name,
                'ss_bindtime' => date('Y-m-d H:i:s')
            ]);
        if ($res) {
            Db::name('phonecode')->where(['phone' => $phone, 'status' => 0, 'type' => 1])->setField('status',1);
            return json(['status' => 200, 'msg' => '绑定成功']);
        } else {
            return json(['status' => 100, 'msg' => '绑定失败']);
        }
    }
    //-------------------------------------------------------------------------------------------------
    //------------------专为达标统计用的----------------------------------------------
    //-------------------------------------------------------------------------------------------------
    public function tjDoneAdmin()
    {
        set_time_limit(0);
        $datas = Db::name('record')
            ->where('record_status',2)
            ->where('record_type','<>',2)
            ->where('record_pay_month',null)
            ->field('record_id,record_pay_time')
            ->select ();
        foreach ($datas as $k => $v){
            $month = substr($v['record_pay_time'],0,7);
            Db::name('record')->where('record_id',$v['record_id'])->setField('record_pay_month',$month);
        }
        //-----------------------------------------------------------------
        $lists = Db::name('record r')
            ->join("up_shop_ercode sc",'r.record_shop_id = sc.ss_shop_id','left')
            ->where('record_status',2)
            ->where('record_type','<>',2)
            ->where('record_pay_month_status',1)
            ->group('record_shop_id,record_pay_month')
            ->field('r.*,sc.ss_shop_id,sc.ss_bindtime')
            ->order('record_add_time DESC')
            ->select ();
//        dump($lists);die;
        if($lists){
            foreach ($lists as $k => $v){
                $nums = 0;
                $users = 0;
                if($v['ss_bindtime']){
                    $users = Db::name('record')
                        ->where('record_status',2)
                        ->where('record_type','<>',2)
                        ->where('record_money','>=',5)
                        ->where('record_add_time','>=',$v['ss_bindtime'])
                        ->where('record_pay_month',$v['record_pay_month'])
                        ->where('record_shop_id',$v['record_shop_id'])
                        ->group('record_user_id')
                        ->count();
                    $nums = Db::name('record')
                        ->where('record_status',2)
                        ->where('record_type','<>',2)
                        ->where('record_pay_month',$v['record_pay_month'])
                        ->where('record_shop_id',$v['record_shop_id'])
                        ->count();
                }

                $update = [
                    'record_pay_month_status' => 2
                ];
                if($users >= 20 && $nums >= 100) {
                    $update['record_pay_month_done'] = 2;
                };
                Db::name('record')
                    ->where('record_status',2)
                    ->where('record_type','<>',2)
                    ->where('record_pay_month',$v['record_pay_month'])
                    ->where('record_shop_id',$v['record_shop_id'])
                    ->update($update);
            }
        }
        exit();
    }
}